﻿using System;
using System.Collections.Generic;

namespace oqis.core.common.file
{
	/// <summary>	
	/// 文件对象操作方法
	/// </summary>
	public class FileOperator
    {
        #region 类初始化与构建

        /// <summary>
		/// 文件操作
		/// </summary>
		public FileOperator()
		{
			//
			// TODO: 对象构建
			//
        }

        #endregion

        #region 文件读取

        /// <summary>
        /// 读取文件流
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>返回二进制数据</returns>
        public byte[] ReadFileStreamToByte(string filePath)
        {
            // 判断
            if (System.IO.File.Exists(filePath) == false) return null;

            // 读取文件流
            System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            int dataLength = (int)fileStream.Length;
            byte[] byteData = new byte[dataLength];
            // 读取
            fileStream.Read(byteData, 0, dataLength);

            // 关闭
            fileStream.Close();
            fileStream.Dispose();

            // 返回结果
            return byteData;
        }
        /// <summary>
        /// 读取文本文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>返回一个集合</returns>
        public IList<string> ReadTxtFileContent(string filePath)
        {
            // 判断
            if (System.IO.File.Exists(filePath) == false) return null;

            // 读取文件
            System.IO.StreamReader txtReader = new System.IO.StreamReader(filePath, System.Text.Encoding.GetEncoding("18030"));

            // 集合
            IList<string> linesList = new List<string>();

            string txtLine = "";//=txtReader.ReadLine();
            while ((txtLine = txtReader.ReadLine()) != null)
            {
                // 添加
                linesList.Add(txtLine);
            }

            // 返回结果
            return linesList;
        }

        #endregion

        /// <summary>
		/// 删除电脑上的临时文件夹下面的文件
		/// </summary>
		public void DeleteTemporaryFiles()
		{
			// 临时文件夹位置
			string[] tempDirs=new string[4];
			tempDirs.SetValue(System.Environment.GetEnvironmentVariable("Temp"),0);
			tempDirs.SetValue(System.Environment.GetEnvironmentVariable("TMP"),1);
			// IE临时文件夹
			tempDirs.SetValue(System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache),2);
			// 最近文件夹
			tempDirs.SetValue(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Recent),3);
			
			string[] subFolders,subFiles;
			string dir;

			// 循环
			for (int i=0;i<tempDirs.Length;i++)
			{				
				dir=tempDirs[i];

				// 判断文件夹是否存在
				if (!System.IO.Directory.Exists(dir)) continue;

				// 子文件夹
				subFolders=System.IO.Directory.GetDirectories(dir);
				for (int j=0;j<subFolders.Length;j++)
				{
					try
					{
						// 删除
						System.IO.Directory.Delete(subFolders[j],true);
					}
					catch
					{
					}
				}

				subFiles=System.IO.Directory.GetFiles(dir);
				for (int j=0;j<subFiles.Length;j++)
				{
					try
					{
                        // 删除
						System.IO.File.Delete(subFiles[j]);
					}
					catch
					{
					}
				}				
			}
		}
		/// <summary>
		/// 检查字符串是否全部为数字--不建设使用这个方法
		/// </summary>
		/// <param name="inputString">输入的字符串</param>
		/// <returns>如果全是数字返回True,否则False</returns>
		public bool IsStringNumeric(string inputString)
		{
			// 判断
			if (inputString==null || inputString=="") return false;

			// 得到每一个字符
			char[] chars=inputString.ToCharArray();
			// 循环判断
			for (int i=0;i<chars.Length;i++)
			{
				try
				{
					// 转换成数字
					Convert.ToInt32(chars[i]);
				}
				catch
				{
                    // 返回结果
					return false;
				}
			}

			// 返回结果
			return true;
		}
		/// <summary>
		/// 获得垃圾文件
		/// </summary>
		/// <param name="fileType">文件类型</param>
		/// <returns>返回一个集合</returns>
		public IList<string> GetRubbishFiles(string[] fileType){
			//System.IO.Directory.GetFiles("C:\\","*.txt");
			return null;
		}	

		/// <summary>
		/// 得到选择的文件夹路径
		/// </summary>
		/// <param name="showNewButton">是否显示新建文件夹按钮</param>
		/// <returns>返回路径值</returns>
		public string GetSelectedFolder(bool showNewButton){
			// 定义一个文件夹选择对话框
			string path="";
			System.Windows.Forms.FolderBrowserDialog folderBrowser=new System.Windows.Forms.FolderBrowserDialog();
			folderBrowser.ShowNewFolderButton=showNewButton;
			folderBrowser.RootFolder=System.Environment.SpecialFolder.MyComputer;
            folderBrowser.Description = "请选择符合您要求的文件夹：";
		    
			// 选择
			if (folderBrowser.ShowDialog()== System.Windows.Forms.DialogResult.OK){
				path=folderBrowser.SelectedPath;
			}
			folderBrowser.Dispose();
			
			// 返回结果
			return path;
		}	
		/// <summary>
		/// 得到选定的文件
		/// </summary>
		/// <param name="filter">文件类型</param>
		/// <returns>返回一个集合,包含所有选定的文件的路径值</returns>
		public string[] GetSelectedFiles(string filter){
			// 设置打开文件对话框
			System.Windows.Forms.OpenFileDialog openFile=new System.Windows.Forms.OpenFileDialog();
			openFile.CheckFileExists=true;
			openFile.CheckPathExists=true;
			openFile.InitialDirectory=System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyComputer);
			openFile.Multiselect=true;
            if (filter.Split(new char[] { '|' }).Length <= 1) filter += "|" + filter;
            openFile.Filter = filter;
            openFile.FilterIndex = 0;

            string[] files=null;
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                files=openFile.FileNames;
            }
            openFile.Dispose();

			// 返回结果
			return files;			
		}		
		/// <summary>
		/// 得到选定的单个文件路径
		/// </summary>
		/// <param name="filter">文件类型</param>
		/// <returns>返回选定的路径值</returns>
		public string GetSelectedFile(string filter){
            // 定义文件选择器
			System.Windows.Forms.OpenFileDialog openFile=new System.Windows.Forms.OpenFileDialog();
			openFile.CheckFileExists=true;
			openFile.CheckPathExists=true;
			openFile.InitialDirectory=System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyComputer);
			openFile.Multiselect=false;
            if (filter.Split(new char[] { '|' }).Length <= 1) filter += "|"+filter;
			openFile.Filter=filter;
			
			string selectedFile="";
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                // 文件名
                selectedFile = openFile.FileName;
            }
            openFile.Dispose();
            
			// 返回结果
			return selectedFile;
		}
        /// <summary>
        /// 得到保存文件的路径
        /// </summary>
        /// <param name="singleFilter">文件筛选类型</param>
        /// <returns>返回文件路径</returns>
        public string GetSaveAsFile(string singleFilter)
        {
            // 定义文件选择器
            System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
            openFile.CheckFileExists =false;
            openFile.CheckPathExists = true;
            openFile.ValidateNames = true;
            openFile.InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyComputer);
            openFile.Multiselect = false;
            openFile.AddExtension = true;
            openFile.Filter = singleFilter + "|" + singleFilter;

            string selectedFile = "";
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // 文件名
                selectedFile = openFile.FileName;
            }
            openFile.Dispose();

            // 返回结果
            return selectedFile;
        }
        /// <summary>
        /// 加密输入的字符串到Ascii码
        /// </summary>
        /// <param name="sourceCode">源字符</param>
        /// <returns>加密后的字符</returns>
        public string EncryptToASCIICode(string sourceCode) {
            if (sourceCode == null || sourceCode == "") return "";

            byte[] asciiBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sourceCode);
            string resultNO = "";
            foreach (byte b in asciiBytes)
            {
                resultNO +=b.ToString().PadLeft(3,'0');
            }
            return resultNO;
        }
        /// <summary>
        /// 解译输入的加密字符
        /// </summary>
        /// <param name="sourceCode">加密字符</param>
        /// <returns>解译结果</returns>
        public string DecryptFromASCIICode(string sourceCode)
        {
            // 判断
            if (sourceCode == null || sourceCode == "") return "";
            // 字符长度
            int codeLen = sourceCode.Length;
            int letterLen = codeLen / 3;

            // 定将数组
            byte[] asciiCodes = new byte[letterLen];
            byte letter;

            for (int i = 0; i < letterLen; i++) {
                letter =Convert.ToByte(sourceCode.Substring(i * 3, 3));
                asciiCodes.SetValue(letter, i);
            }

            string result = System.Text.ASCIIEncoding.ASCII.GetString(asciiCodes);
            return result;
        }
        /// <summary>
        /// 得到输出路径
        /// </summary>
        /// <param name="fullFilter">文件类型过滤器</param>
        /// <returns>返回选定的路径</returns>
        public string GetOpenFilePath(string fullFilter)
        {
            System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
            openFile.Title = "选择输出路径";
            openFile.CheckPathExists = true;
            openFile.CheckFileExists = true;
            openFile.Filter = fullFilter;
            openFile.FilterIndex = 0;
            openFile.Multiselect = false;
            openFile.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) return openFile.FileName;
            else return "";
        }
        /// <summary>
        /// 得到保存文件的路径
        /// </summary>
        /// <param name="fullFilter">文件类型过滤器</param>
        /// <returns>返回指定的文件名</returns>
        public string GetSaveFilePath(string fullFilter)
        {
            string ext = ".txt";
            string[] filters = fullFilter.Split(new char[] { '|' });
            ext = filters[filters.Length - 1];

            System.Windows.Forms.SaveFileDialog saveFile = new System.Windows.Forms.SaveFileDialog();
            saveFile.Title = "请选择保存路径";
            saveFile.AddExtension = true;
            saveFile.CheckFileExists = false;
            saveFile.CheckPathExists = true;
            saveFile.DefaultExt = ext;
            saveFile.Filter = fullFilter;
            saveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            saveFile.ValidateNames = true;

            if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) return saveFile.FileName;
            else return "";
        }

    }
    /// <summary>
    /// 日志记录
    /// </summary>
    public class LogRecorder
	{
		/// <summary>
		///  类的初始化
		/// </summary>
		public LogRecorder()
		{

		}

		/// <summary>
		/// 日志记录
		/// </summary>
		/// <param name="logFile">日志文件路径</param>
		/// <param name="functionName">函数名称</param>
		/// <param name="errorInfo">错误信息</param>
		public void RecordErrorLog(string logFile,string functionName,string errorInfo)
		{
            // 文件流写入器
            System.IO.StreamWriter streamWriter = null;			
			if (!System.IO.File.Exists(logFile)) streamWriter = System.IO.File.CreateText(logFile);
			else streamWriter = System.IO.File.AppendText(logFile);		
            if (streamWriter == null) return;

			// 记录
			streamWriter.WriteLine("操作时间: " + System.DateTime.Now.ToString());
			streamWriter.WriteLine("函数名称: " + functionName);
			streamWriter.WriteLine("错误信息: " + errorInfo);
			streamWriter.WriteLine();

			// 写入
			streamWriter.Flush();
			streamWriter.Close();	
		}
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="logFile">日志文件路径</param>
        /// <param name="functionName">函数名称</param>
        /// <param name="ex">出错信息</param>
        public void RecordErrorLog(string logFile, string functionName, Exception ex) {
            // 文件流写入器
            System.IO.StreamWriter streamWriter = null;
            if (!System.IO.File.Exists(logFile)) streamWriter = System.IO.File.CreateText(logFile);
            else streamWriter = System.IO.File.AppendText(logFile);
            if (streamWriter == null) return;

            // 记录
            streamWriter.WriteLine("操作时间: " + System.DateTime.Now.ToString());
            streamWriter.WriteLine("函数名称: " + functionName);
            streamWriter.WriteLine("错误来源: " + ex.Source);
            streamWriter.WriteLine("错误信息: " + ex.Message);
            streamWriter.WriteLine();

            // 写入
            streamWriter.Flush();
            streamWriter.Close();
        }
	}
}
